#include "cy8tmg120.h"
#include "stm32f1xx_hal.h"

#include "my_log.h"


#pragma pack(1)

typedef struct
{
    uint8_t x1H;
    uint8_t x1L;
    uint8_t y1H;
    uint8_t y1L;
    uint8_t x2H;
    uint8_t x2L;
    uint8_t y2H;
    uint8_t y2L;
    uint8_t fingerCount;
    uint8_t gesture;
    
}Point_Data_t;


#pragma pack()



extern I2C_HandleTypeDef hi2c1;

static bool readDataFlag = false;


static void Reset_Touch(void)
{
    HAL_GPIO_WritePin(GPIOB, GPIO_PIN_4, GPIO_PIN_SET);
    HAL_Delay(10);
    HAL_GPIO_WritePin(GPIOB, GPIO_PIN_4, GPIO_PIN_RESET);
    HAL_Delay(10);
}



static inline void Write_Reg(uint8_t reg, uint8_t dat)
{
    HAL_I2C_Mem_Write(&hi2c1, (0x05<<1), reg, 1, &dat, 1, 10);
}

static inline uint8_t Read_Reg(uint8_t reg)
{
    uint8_t dat = 0;
    HAL_I2C_Mem_Read(&hi2c1, (0x05 << 1) | 0x01, reg, 1, (uint8_t*)&dat, 1, 10);
    return dat;
}


void Clear_INT_Flag(void)
{
    if(Read_Reg(0x07) != 0x01)
        Write_Reg(0x07, 0x01);
}

void MX_I2C1_Init(void);

void TMG120_Init(void)
{
    HAL_I2C_DeInit(&hi2c1);     // 复位前先反初始化I2C以避免STM32F103硬件I2C的bug
    Reset_Touch();
    MX_I2C1_Init();
    Write_Reg(0x04, 0x09);      // Close low power mode
    log_i("CSR: %02X", Read_Reg(0x04));
}


uint8_t TMG120_ReadFwVer(void)
{
    uint16_t ver = 0;
    ver = Read_Reg(0x03);
    
    log_i("TMG120_ReadFwVer: %02X", ver);
    
    ver = Read_Reg(0x04);
    log_i("CSR: %02X", ver);
    
    return ver;
}


void TMG120_ReadPointData(void)
{
    Point_Data_t point;
    uint16_t x,y,x1,y1;
    HAL_I2C_Mem_Read(&hi2c1, (0x05 << 1) | 0x01, 0x09, 1, (uint8_t*)&point, 10, 10);
    
    //log_i("point:\t%d", point.fingerCount);
    //log_i("gesture:\t%02X", point.gesture);
    x = point.x1H * 0xff + point.x1L;
    y = point.y1H * 0xff + point.y1L;
    x1 = point.x2H * 0xff + point.x2L;
    y1 = point.y2H * 0xff + point.y2L;
    log_i("\t%d\t%d\t%d\t%d", x, y, x1, y1);
}


void TMG120_DataHandle(void)
{
    if(readDataFlag)
    {
        Clear_INT_Flag();
        TMG120_ReadPointData();
        readDataFlag = false;
    }
}



void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin)
{
    if(GPIO_Pin == GPIO_PIN_5)
    {
        readDataFlag = true;
    }
}

